package com.sumainfor.pc.cfo.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.cfo.dao.InvoiceMapper;
import com.sumainfor.pc.cfo.dao.UtilsMapper;
import com.sumainfor.pc.cfo.service.InvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Meng
 * @ClassName InvoiceServiceImpl
 * @date 2019/4/28 16:14
 * @description: TODO
 */
@Service
public class InvoiceServiceImpl implements InvoiceService {

    private ReentrantLock lock = new ReentrantLock(false);

    @Autowired
    public InvoiceMapper invoiceMapper;

    @Autowired
    UtilsMapper UtilsMapper;

    String UUID = null;

    @Override
    public List<Map<String, Object>> listTenantHaveInvoiceBill(Map<String, Object> params) {
        return invoiceMapper.listTenantHaveInvoiceBill(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertInvoiceInfo(Map<String, Object> params) {
        boolean result = false;
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                Map<String, Object> uuid = UtilsMapper.getUUID(new HashMap<String, Object>() {{
                    put("uuid", "InvoId");
                    put("database", Constants.DATA_SOURCE_CFO);
                    put("surface", "tccfo_invoice");
                }});
                if (uuid != null) {
                    int number = Integer.valueOf(uuid.get("uuid").toString());
                    UUID = ComUtils.getLocalTrmSeqNum("fp", number);
                } else {
                    UUID = ComUtils.getLocalTrmSeqNum("fp", 0);
                }
                //所有新增处理
                Map<String, Object> commonInsertParms = new HashMap<String, Object>();
                commonInsertParms.put("InvoId", UUID);//发票主编号
                commonInsertParms.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                commonInsertParms.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(commonInsertParms);

                //公司在职证明图片集合（个人租客开增值税普通发票和专用发票）
                String InService = null;
                StringBuffer stringBuffer = new StringBuffer();
                List<String> InServicelist = (List<String>) params.get("InService");
                if (InServicelist.size() > 0) {
                    for (String str : InServicelist) {
                        stringBuffer.append(str).append(",");
                    }
                    stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                    InService = stringBuffer.toString();
                }
                params.put("InService", InService);
                params.put("ApplyTime", ConvertDateTime.getCurrentTime());
                params.putAll(commonInsertParms);
                //新增发票申请表主表
                invoiceMapper.insertInvoice(params);

                //发票申请详表
                List<Map<String, Object>> invoice = (List<Map<String, Object>>) params.get("invoiceinfo");
                for (Map<String, Object> map : invoice) {
                    map.putAll(commonInsertParms);
                    if (invoiceMapper.getInvoiceCount(map) != 0) {
                        throw new TCException("您已申请过开票了,不可重复开票!");
                    }
                    //新增发票申请表详表
                    invoiceMapper.insertInvoiceInfo(map);
                }
                result = true;
            } catch (NumberFormatException e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

}
